<?php


namespace app\common\cachemodel;


use app\common\lib\exception\ApiException;
use app\common\model\BaseCache;
use think\Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlcrCustomReportQuestionComment extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_custom_report_question_comment';

    protected $cacheModel = 'custom_report.question_comment';

    /**
     * 添加报告评论
     * @param array $data
     * @throws ApiException
     */
    public function saveData(array $data)
    {
        try
        {
            $this->insertGetId($data);
            if ($data['level'] >= 3)
            {
                CacheManage::getInstance()->setCacheConfig('astr_admin.astr', 0)->rmCache('list');//删除报告首页占星师列表缓存
            }
        }
        catch (\Exception $e)
        {
            Log::write('报告评论添加失败：' . $e->getMessage() . PHP_EOL . '请求参数：' . \GuzzleHttp\json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL . '失败行数：' . $e->getFile() . '-' . $e->getLine(), 'error', true);
            throw new ApiException('服务异常，请稍后重试', 200, 0);
        }
    }

    /**
     * 获取对应的问题评论信息
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $where = ['qid' => ['in', $ids]];
        $field = 'qid,level,tid,comment,astr_id,create_time,status';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'qid');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取好评率
     * @param int $astrId
     * @return string
     * @throws Exception
     */
    public function getRating(int $astrId)
    {
        $allNum = $this->where('astr_id', $astrId)->where('appeal_status', 0)->whereIn('status', [2, 3])->count();
        if ($allNum)
        {
            $rightNum = $this->where('astr_id', $astrId)->where('appeal_status', 0)->whereIn('status', [2, 3])->where('level', '>', 2)->count();

            return sprintf("%.1f", ($rightNum / $allNum) * 100);
        } else
        {
            return "100";
        }
    }
}
